<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'exceptions/tangra_module_exception.class.php');

/**
 * Will add variable and value as /var/value/ as suffix to all hrefs and form "action"s. Similar to PHP's function output_add_rewrite_var.
 *
 * @param string $var Must be lower case, starting with letter, 50 simbols max (a-z0-9_)
 * @param string $value
 * @param boolean $forgiving If false on attempt for adding duplicate var will  throw exception
 */
function output_add_pi_rewrite_var($var_name, $value, $forgiving = false) {
	global $_pi_rewrite_vars;

	if (!ereg("^[a-z_]{1}[a-z0-9_]{0,50}$", $var_name)) {
		throw new Tangra_Module_Exception('Invalid variable name. Must be lower case, starting with letter, 50 simbols max (a-z0-9_). Current value: '.$var_name);
	}

	if (array_key_exists($var_name, $_pi_rewrite_vars)) {
		if ($forgiving) {
			$_pi_rewrite_vars[$var_name] = $value;
		}  else {
			throw new Tangra_Module_Exception('PI rewrite var already exist. Var: '.$var_name);
		}
	} else {
		$_pi_rewrite_vars[$var_name] = $value;
	}

}


function _perform_pi_rewrite($content) {
	global $_pi_rewrite_vars_container;

	$pi_string = _get_pi_string();

	if ($pi_string) {
		$output = ereg_replace("(href|action)='(([^/])[[:alnum:]/+=%&;_.~-]*)([?]{0,1}[[:alnum:]+=%&;_.~-]*)'", '\1="\2'.'\4'.'"', $content);

		$output = ereg_replace("(href|action)=\"(([^/])[[:alnum:]/+=%&;_.~-]*)([?]{0}[[:alnum:]+=%&;_.~-]*)/\"", '\1="\2'.'/'.$pi_string.'\4'.'"', $output);
		$output = ereg_replace("(href|action)=\"(([^/])[[:alnum:]/+=%&;_.~-]*)([?]{0}[[:alnum:]+=%&;_.~-]*)([^/])\"", '\1="\2\5'.'/'.$pi_string.'\4'.'"', $output);
		$output = ereg_replace("(href|action)=\"(([^/])[[:alnum:]/+=%&;_.~-]*)/([?]{1}[[:alnum:]+=%&;_.~-]*)([^/])\"", '\1="\2'.'/'.$pi_string.'\4\5'.'"', $output);
		$output = ereg_replace("(href|action)=\"(([^/])[[:alnum:]/+=%&;_.~-]*)([^/])([?]{1}[[:alnum:]+=%&;_.~-]*)([^/])\"", '\1="\2\4'.'/'.$pi_string.'\5\6'.'"', $output);

		return $output;
	} else {
		return $content;
	}
}


function _get_pi_string() {
	global $_pi_rewrite_vars;

	$ret = '';

	foreach($_pi_rewrite_vars as $var => $value) {
		$ret .= $var.'-'.urlencode($value).'/';
	}

	return $ret;
}